import { defineStore } from 'pinia';
import { reactive, toRefs } from 'vue';

import { getToken, removeToken, setToken } from 'src/utils';
import loginApi, { LoginForm, MenuVO } from 'src/api/login';

type UserState = {
  token: string;
  username: string;
  nickname: string;
  avatar: string;
  roles: string[];
  permissions: string[];

  menus: MenuVO[];

  // routes: RouteRecordRaw[];
  // // 动态路由的移除函数
  // removeRoutes: (() => void)[];
};

export const useUserStore = defineStore('user', () => {
  // state
  const state = reactive<UserState>({
    token: getToken() || '',
    username: '',
    nickname: '',
    avatar: '',
    roles: [],
    permissions: [],

    menus: [],

    // routes: [],
    // removeRoutes: [],
  });

  // 登录
  function doLogin(form: LoginForm) {
    return new Promise<string>((resolve, reject) => {
      loginApi
        .doLogin(form)
        .then((accessToken) => {
          state.token = accessToken;
          setToken(accessToken);
          resolve(accessToken);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 登出
  function doLogout() {
    return new Promise<void>((resolve) => {
      loginApi.doLogout().finally(() => {
        clearData();
        resolve();
      });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  const getUserInfo = (): Promise<{ roles: string[]; perms: string[] }> => {
    return new Promise(async (resolve, reject) => {
      loginApi
        .getLoginUser()
        .then((data) => {
          state.username = data.username;
          state.nickname = data.nickname;
          state.avatar = data.avatar;
          state.roles = data.roles;
          state.permissions = data.permissions;
          state.menus = data.menus;

          //state.removeRoutes = [];

          // const { routes, menus } = convertRouteMenus(data.routes);
          // state.routes = routes;
          // menus.unshift({ title: '首页', path: '/', icon: 'home' });

          resolve({ roles: data.roles, perms: data.permissions });
        })
        .catch((error) => {
          reject(error);
        });
    });
  };

  // 刷新token
  function refreshToken(newToken: string) {
    state.token = newToken;
    setToken(newToken);
  }

  function clearData() {
    state.token = '';
    removeToken();

    state.username = '';
    state.nickname = '';
    state.avatar = '';
    state.roles = [];
    state.permissions = [];

    state.menus = [];
    // state.routes = [];

    // // 移除动态路由
    // state.removeRoutes.forEach((r) => r());
    // state.removeRoutes = [];
  }

  return { ...toRefs(state), doLogin, doLogout, getUserInfo, refreshToken };
});

// /**
//  * 根据后端返回的菜单路由生成动态路由和菜单数据
//  *
//  * @param accessMenus 接口返回的有权限的路由菜单
//  * @returns 动态路由,菜单
//  */
// const Layout = () => import('src/layouts/MainLayout.vue');
// const ParentView = () => import('src/components/ParentView.vue');
// const modules = import.meta.glob('../../pages/**/**.vue');
// function convertRouteMenus(accessMenus: RouteMenu[], basePath = '') {
//   const menus: MenuVO[] = [];
//   const routes: RouteRecordRaw[] = [];

//   for (const m of accessMenus) {
//     const { routes: croutes, menus: cmenus } = convertRouteMenus(m.children, m.path);
//     // 处理路由：路由必须有component属性。比如外部链接的情况,仅是一个菜单，不需要加路由
//     if (m.component && m.path) {
//       const route: RouteRecordRaw = { name: m.name, path: m.path, meta: { ...m.meta }, redirect: m.redirect, children: [] };
//       if (m.component.toString() === 'Layout') {
//         route.component = Layout;
//       } else if (m.component.toString() === 'ParentView') {
//         route.component = ParentView;
//       } else {
//         // eslint-disable-next-line @typescript-eslint/no-explicit-any
//         const component = modules[`../../pages/${m.component}.vue`];
//         route.component = component ?? modules['../../pages/Error404.vue'];
//       }
//       route.children = croutes;
//       routes.push(route);
//     }

//     // 处理菜单
//     if (m.meta && m.meta.title && m.meta.hidden !== true) {
//       const menu: MenuVO = {
//         // 完整路径 = 父级路径(/level/level_3) + 路由路径
//         path: resolvePath(m.path, basePath),
//         title: m.meta.title,
//         icon: m.meta.icon,
//         isLink: isExternal(m.path),
//         children: cmenus,
//       };
//       menus.push(menu);
//     }
//   }

//   return { menus, routes };
// }

// function resolvePath(routePath: string, basePath: string) {
//   if (isExternal(routePath)) {
//     return routePath;
//   }
//   if (isExternal(basePath)) {
//     return basePath;
//   }

//   // 完整路径 = 父级路径(/level/level_3) + 路由路径
//   const fullPath = basePath + (routePath.startsWith('/') ? '' : '/') + routePath;
//   return fullPath;
// }

// function isExternal(path: string): boolean {
//   return /^(https?:|http?:|mailto:|tel:)/.test(path);
// }
